import axios, { AxiosHeaders } from 'axios'
import type { AxiosRequestConfig } from 'axios'

import { Dialog } from 'vant'

// 创建 axios 实例
const service = axios.create({
  baseURL: 'http://47.94.148.165:3001/api',
  timeout: 10000
})

interface myAxiosRequestConfig extends AxiosRequestConfig {
  headers: { token?: string | null }
}


service.interceptors.request.use((config: AxiosRequestConfig) => {
  if (config.url === '/user/info') {
    (config as myAxiosRequestConfig).headers.token = window.localStorage.getItem('token')
  }

  if (/^\/cart/.test(config.url as string)) {
(config as myAxiosRequestConfig).headers.token = window.localStorage.getItem('token')
  }
  if (config.url === '/user/orderlist') {
    (config as myAxiosRequestConfig).headers.token = window.localStorage.getItem('token')
  }
  return config
})

service.interceptors.response.use(
  response => {
    if (response.data.code === '10119') {
      Dialog({
        title: '提示',
        message: '您登录状态有问题, 请重新登录'
      })

      return { code: 0 }
    }

    return response.data
  },
  err => {
    Dialog.alert({ title: '网络错误', message: '网络不给力, 稍后再来' })
  }
)
export default service